package com.system.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.system.entity.User;
import com.system.util.CloseResourceUtil;
import com.system.util.GetConnectionUtils;

public class UserDaoImpl implements IUserDao {

	public String checkUser(User user) throws SQLException {
		Connection connection = GetConnectionUtils.getoneConnection();
		String sql = "SELECT * FROM user WHERE username = ?";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		
		preparedStatement.setString(1, user.getName());
		ResultSet result = preparedStatement.executeQuery();
		if (result.next()) {
			String password = result.getString("password");
			if (password != null && password.equals(user.getPassword())) {		
				CloseResourceUtil.close(connection, preparedStatement, result);
				return user.getName();
			}
		}
		CloseResourceUtil.close(connection, preparedStatement, result);
		return null;
		
	}

	public String changePassword(String username, String password) throws SQLException {
		Connection connection = GetConnectionUtils.getoneConnection();
		String sql = "UPDATE user SET password = ? WHERE username = ?";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		preparedStatement.setString(1, password);
		preparedStatement.setString(2, username);
		if (preparedStatement.executeUpdate() > 0) {
			CloseResourceUtil.close(connection, preparedStatement, null);
			return "1";
		} else {
			CloseResourceUtil.close(connection, preparedStatement, null);
			return "0";
		}
	}

}
